Fork me on GitHub

344. Reverse String

\344. Reverse String

Easy

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

1
2
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

1
2
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
  1. two pointer (one while loop)
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if not s: return
lo = 0
hi = len(s)-1
while(lo <= hi):
s[lo], s[hi] = s[hi], s[lo]
lo += 1
hi -= 1
  1. one for loop
1
2
3
4
5
6
7
8
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if not s: return
for i in range(len(s) // 2):
s[i], s[-i-1] = s[-i-1], s[i]
Shuolin Tian wechat
欢迎加我微信交流